package com.wkbb.common.handler;

import com.wkbb.common.utils.TimeUtil;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.*;
import java.util.Calendar;

public class CalendarTypeHandler extends BaseTypeHandler<Calendar> {

//	@Override
//	public void setParameter(PreparedStatement ps, int i, Calendar parameter, JdbcType jdbcType) throws SQLException {
//		ps.setTimestamp(i, new Timestamp(parameter.getTimeInMillis()));
//	}
//
//	@Override
//	public Calendar getResult(ResultSet rs, String columnName) throws SQLException {
//		Timestamp time = rs.getTimestamp(columnName);
//		Calendar c = Calendar.getInstance();
//		c.setTimeInMillis(time.getTime());
//		return c;
//	}
//
//	@Override
//	public Calendar getResult(ResultSet rs, int columnIndex) throws SQLException {
//		Timestamp time = rs.getTimestamp(columnIndex);
//		Calendar c = Calendar.getInstance();
//		c.setTimeInMillis(time.getTime());
//		return c;
//	}
//
//	@Override
//	public Calendar getResult(CallableStatement cs, int columnIndex) throws SQLException {
//		Timestamp time = cs.getTimestamp(columnIndex);
//		Calendar c = Calendar.getInstance();
//		c.setTimeInMillis(time.getTime());
//		return c;
//	}

	@Override
	public void setNonNullParameter(PreparedStatement ps, int i, Calendar parameter, JdbcType jdbcType)
			throws SQLException {
		if(parameter==null) {
			ps.setNull(i, Types.VARCHAR);
		}else {
			ps.setTimestamp(i, TimeUtil.toTimestamp(parameter));
		}
	}

	@Override
	public Calendar getNullableResult(ResultSet rs, String columnName) throws SQLException {
		return getCalendar(rs.getTimestamp(columnName));
	}

	@Override
	public Calendar getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
		return getCalendar(rs.getTimestamp(columnIndex));
	}

	@Override
	public Calendar getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
		return getCalendar(cs.getTimestamp(columnIndex));
	}
	
	private Calendar getCalendar(Timestamp timestamp) {
		if (timestamp == null) {
			return null;
		}
		return TimeUtil.toCalendar(timestamp);
	}
}
